<template>
  <div id="app">
    <h1>设备检测</h1>
    <div id="local-stream" ref="localStream"></div>
    <button @click="checkDevices">检测设备</button>
  </div>
</template>
<script>
import { ref, onMounted, onUnmounted } from "vue";
import AgoraRTC from "agora-rtc-sdk-ng";

export default {
  name: "DeviceCheck",
  setup() {
    const localStream = ref(null);
    let videoElement = null;
    let tracks = [];

    const checkDevices = async () => {
      try {
        // 创建音视频轨道
        tracks = await AgoraRTC.createMicrophoneAndCameraTracks();

        // 获取原生 MediaStreamTrack
        const cameraTrack = tracks[1].getMediaStreamTrack(); // 视频轨道
        const microphoneTrack = tracks[0].getMediaStreamTrack(); // 音频轨道

        // 创建 video 元素
        videoElement = document.createElement("video");
        videoElement.autoplay = true;
        videoElement.muted = true;
        videoElement.width = 400;
        videoElement.height = 300;

        // 创建 MediaStream
        const stream = new MediaStream([cameraTrack, microphoneTrack]);
        videoElement.srcObject = stream;

        // 显示摄像头画面
        if (localStream.value) {
          localStream.value.appendChild(videoElement);
        }

        alert("请检查您的摄像头和麦克风是否正常工作。");
      } catch (error) {
        console.error("设备检测失败:", error);
        alert("设备检测失败，请检查您的设备连接。");
      }
    };

    const cleanup = () => {
      // 使用 AgoraRTC 推荐的方式关闭轨道
      tracks.forEach((track) => track.close());
      tracks = [];

      if (videoElement) {
        videoElement.srcObject = null;
        if (localStream.value && videoElement.parentNode === localStream.value) {
          localStream.value.removeChild(videoElement);
        }
        videoElement = null;
      }
    };

    onMounted(() => {
      localStream.value = document.getElementById("local-stream");
    });

    onUnmounted(() => {
      cleanup();
    });

    return {
      localStream,
      checkDevices,
    };
  },
};
</script>

<style>
#app {
  text-align: center;
}

#local-stream {
  width: 400px;
  height: 300px;
  border: 1px solid #ccc;
  margin: 20px auto;
}
</style>
